import Vue from 'vue'
import Vuex from 'vuex'
import { login } from '@/api/user'
import { connectGraph } from '@/api/graph'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    nav: {
      showLoginModal: false,
      showConnectModal: false
    },
    curGraph: null,
    user: {
      role: null,
      name: null,
      graphs: [],
      isLogin: false
    }
  },
  getters: {
    user: state => ({
      role: state.user.role,
      name: state.user.name,
      graphs: state.user.graphs,
      isLogin: state.user.isLogin
    }),
    curGraph: state => state.curGraph,
    isNavShowModal: state => state.nav.showLoginModal || state.nav.showConnectModal
  },
  mutations: {
    UPDATE_NAV (state, { field, value }) {
      state.nav = {
        ...state.nav,
        [field]: value
      }
    }
  },
  actions: {
    // 登录
    async loginService ({ state }, { username, password }) {
      const res = await login(username, password)
      if (res.status === 'success') {
        state.user = {
          ...state.user,
          ...res.data,
          isLogin: true
        }
      }
      return {
        status: res.status,
        msg: res.msg
      }
    },
    // 注销
    async logoutService ({ state }) {
      // const res = await logout()
      state.user = {
        ...state.user,
        role: null,
        name: null,
        graphs: [],
        isLogin: false
      }
      state.curGraph = null
      return {
        status: 'success',
        msg: '注销成功'
      }
    },
    // 连接知识图谱
    async connectGraphService ({ state }, { ip, account, pass }) {
      const res = await connectGraph(ip, account, pass)
      if (res.status === 'success') {
        state.curGraph = res.data
      }
      return {
        status: res.status,
        msg: res.msg
      }
    }
  }
})
